﻿using GalaSoft.MvvmLight;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace GuiSearcher.ViewModel.Abstract {
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class AbstractValidatorViewModel : ViewModelBase, INotifyDataErrorInfo {


        #region Constants

        #endregion

        
        #region Private Fields

        private readonly Dictionary<string, ICollection<string>> _validationErrors = new Dictionary<string, ICollection<string>>();

        #endregion


        #region Events

        public event System.EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        #endregion


        #region Constructors

        /// <summary>
        /// Initializes a new instance of the AbstractValidatorViewModel class.
        /// </summary>
        public AbstractValidatorViewModel() {
        }

        #endregion

        
        #region Properties

        public bool HasErrors {
            get {
                throw new System.NotImplementedException();
            }
        }

        #endregion

        
        #region Public Methods

        public System.Collections.IEnumerable GetErrors(string propertyName) {
            throw new System.NotImplementedException();
        }

        #endregion

        #region Protected Methods

        protected void ValidateModelProperty(object value, string propertyName) {
            if (_validationErrors.ContainsKey(propertyName))
                _validationErrors.Remove(propertyName);

            ICollection<ValidationResult> validationResults = new List<ValidationResult>();
            ValidationContext validationContext =
            new ValidationContext(null, null, null) {
                MemberName = propertyName
            };
            if (!Validator.TryValidateProperty(value, validationContext, validationResults)) {
                _validationErrors.Add(propertyName, new List<string>());
                foreach (ValidationResult validationResult in validationResults) {
                    _validationErrors[propertyName].Add(validationResult.ErrorMessage);
                }
            }
            RaiseErrorsChanged(propertyName);
        }

        private void RaiseErrorsChanged(string propertyName) {
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        #endregion


        #region Private Methods

        #endregion





    }
}